<template>
  <div class="car_type__container">
    <div class="car_distance">{{ handleCarDistance }}</div>
    <car-type-price v-for="item in handleDataPrices"
                    :key="item.supplierCd"
                    :data="item"
                    @reservation="onClickReservation"/>
    <p class="not_car" v-show="notHaveUserCar">没有可用的车辆...</p>
  </div>
</template>
<script>
import carTypePrice from './modules/car-type-price/car-type-price'
import * as util from 'utils/utils'
import { car } from '../data'
export default {
  components: { carTypePrice },
  data () {
    return {
      data: {},
      notHaveUserCar: false
    }
  },
  created () {
    this.getCarTypeListData();
    this.getDistanceFn().then(resolve => {
      store.set('USER_CAR_DISTANCE', `预计时长${resolve.duration / 60}分钟，行驶${resolve.distance / 1000}公里`)
    }, reject => {
      this.$vux.toast.show({
        time: 1000,
        type: 'warn',
        text: reject.msg,
        position: 'middle'
      })
    })
  },
  computed: {
    handleDataPrices () {
      if (util.isEmptyObject(this.data)) return [];
      let _data = [];
      let sort = ['经济型', '舒适型', '商务型', '豪华型', '奢华型'];
      let prices = this.data.prices;
      if (!prices) return false;
      Object.keys(prices).forEach(_item => {
        let index = sort.findIndex(a => {
          return a === _item
        });
        let lists = prices[_item].sort((a, b) => {
          return a.price - b.price
        });
        _data[index] = {
          title: _item,
          carTypeUrl: lists[0].carTypeUrl,
          createTime: this.data.createTime,
          lists: lists
        }
      });
      if (_data.notempty().length < 1) {
        this.notHaveUserCar = true
      }
      return _data.notempty()
    },
    handleCarDistance () {
      return store.get('USER_CAR_DISTANCE')
    }
  },
  methods: {
    // 获取数据列表
    getCarTypeListData () {
      let params = store.get('USER_CAR_PARAMS');
      this.$vux.loading.show({
        text: '加载中...'
      });
      car.getEstimatePrice({
        productId: params.productId,
        type: params.type,
        startCityId: params.startAddress.cityId,
        startCityName: params.startAddress.cityName,
        startAddress: params.startAddress.address,
        startAddressDetail: params.startAddress.addressDetail,
        startLongitude: Number(params.startAddress.longitude),
        startLatitude: Number(params.startAddress.latitude),
        endCityId: params.endAddress.cityId,
        endCityName: params.endAddress.cityName,
        endAddress: params.endAddress.address,
        endAddressDetail: params.endAddress.addressDetail,
        endLongitude: Number(params.endAddress.longitude),
        endLatitude: Number(params.endAddress.latitude),
        carUseTime: params.carUserTime,
        landmarkNo: '',
        flightNo: '',
        flightDate: null
      }).then((res) => {
        this.$vux.loading.hide();
        if (res.data.code === 0) {
          this.data = Object.assign({}, res.data.data, {
            createTime: Date.now()
          });
          // 将询价信息保存到本地，将会在叫车后被清空
          store.set('USER_CAR_TYPE_ALL_DATA', this.data)
        } else {
          this.$vux.toast.show({
            time: 1000,
            type: 'warn',
            text: res.msg,
            position: 'middle'
          })
        }
      })
    },
    // 点击预定按钮事件
    onClickReservation (item) {
      if ((Date.now() - item.createTime) / 60000 >= 30) {
        // 询价结果返回时间≥30分钟，在途系统订单生单失败，页面跳转询价失效提示页
        this.$router.push({
          path: `/carIndex/orderError/null`,
          query: {
            state: 3
          }
        });
        // 删除本地询价车辆
        store.remove('USER_CAR_TYPE_ALL_DATA')
      } else {
        // 询价结果返回时间＜30分钟，在途系统订单生单成功，页面跳转等待司机接单页
        this.$store.commit('SET_CREATED_ORDER_DATA', Object.assign(item, {
          preId: this.data.preId
        }));
        store.set('USER_CAR_TYPE_DATA', Object.assign(item, {
          preId: this.data.preId
        }));
        this.$router.push('/carIndex/carDetail')
      }
    },
    // 距离测量
    getDistanceFn () {
      let params = store.get('USER_CAR_PARAMS');
      let startAddress = params.startAddress;
      let endAddress = params.endAddress;
      return new Promise((resolve, reject) => {
        car.getDistance({
          startLocation: `${startAddress.longitude},${startAddress.latitude}`,
          endLocation: `${endAddress.longitude},${endAddress.latitude}`
        }).then(res => {
          if (res.data.code === 0) {
            resolve(res.data.data)
          } else {
            reject(res.data.msg)
          }
        })
      })
    }
  }
}
</script>
<style lang="stylus" type="text/stylus">
  @import "~assets/css/theme"

  .car_type__container
    .car_distance
      text-align center
      font-size $sl_font_size_14
      background #92a9b9
      color #fff
      padding 1 * .61rem 0
    .not_car
      text-align center
      margin 100px 0
      color $sl_font_color_desc
</style>
